package com.example.localalbum.ui

import android.graphics.Bitmap
import android.os.Bundle
import android.os.Environment
import android.support.v4.view.ViewPager
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.centling.smartSealForPhone.R
import com.centling.smartSealForPhone.activity.BaseActivity
import com.centling.smartSealForPhone.utils.GlideApp
import com.centling.smartSealForPhone.utils.ShowToast
import com.example.localalbum.common.LocalImageHelper
import kotlinx.android.synthetic.main.activity_pager_view.*
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException

class PagerView : BaseActivity(){

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_pager_view)

        val intent = intent
        val pictures = intent.getParcelableArrayListExtra<LocalImageHelper.LocalFile>("FILE_LIST")
        val index = intent.getIntExtra("INDEX", 0)

        currentPosition = index

        albumviewpager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float,
                                        positionOffsetPixels: Int) {
                if (albumviewpager.adapter != null) {
                    val text = "${position + 1}/${albumviewpager.adapter?.count ?: 0}"
                    tv_header_bar_photo_count.text = text
                } else {
                    tv_header_bar_photo_count.text = "0/0"
                }
            }

            override fun onPageSelected(position: Int) {
                currentPosition = position
            }

            override fun onPageScrollStateChanged(state: Int) {

            }
        })
        iv_header_bar_photo_back.setOnClickListener { finish() }
        tv_bottom_bar_photo_save.setOnClickListener {
            if (pictures.size != 0 && currentPosition in 0 until pictures.size) {
                GlideApp.with(mContext).asBitmap().load(pictures[currentPosition].originalUri).into(object : SimpleTarget<Bitmap>() {
                    override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                        saveBitmap(resource, "${currentPosition}_${System.currentTimeMillis()}")
                    }
                })
            }
        }

        albumviewpager.adapter = albumviewpager.LocalViewPagerAdapter(pictures)
        albumviewpager.currentItem = index
        tv_header_bar_photo_count.text = "${index + 1}/￥${pictures.size}"
    }

    private var currentPosition = 0

    fun saveBitmap(bitmap: Bitmap, name: String) {
        mProcessDialog.setTitle("正在保存图片").showWithCancel()
        Thread({
            val smartSealDir = File(Environment.getExternalStorageDirectory(), "SmartSeal")
            if (!smartSealDir.exists()) {
                smartSealDir.mkdir()
            }
            try {
                val out = FileOutputStream(File(smartSealDir.absolutePath, "smart_seal_$name.png"))
                bitmap.compress(Bitmap.CompressFormat.JPEG, 80, out)
                out.flush()
                out.close()
                runOnUiThread { ShowToast.shortTime("图片已保存(-> SmartSeal)") }
            } catch (e: FileNotFoundException) {
                e.printStackTrace()
            } catch (e: IOException) {
                e.printStackTrace()
            } finally {
                runOnUiThread { mProcessDialog.dismiss() }
            }
        }).start()
    }
}
